<template>
  <n-modal 
    :show="show" 
    :mask-closable="false" 
    style="width: 90%; max-width: 1200px;"
    @update:show="$emit('update:show', $event)"
  >
    <n-card
      :title="editingRule ? '编辑规则' : '新建规则'"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <template #header-extra>
        <n-button quaternary circle @click="$emit('update:show', false)">
          <template #icon>
            <n-icon :component="CloseOutline" />
          </template>
        </n-button>
      </template>

      <!-- 规则名称编辑 -->
      <rule-name-editor 
        v-model:value="localRule.name"
        class="rule-name-section"
      />

      <!-- 规则内容区域 -->
      <div class="rule-content">
        <!-- 规则条件编辑区 -->
        <div class="rule-left">
          <rule-condition-section 
            v-model:value="localRule.condition"
            @error="handleConditionError"
          />
        </div>

        <!-- 规则行为编辑区 -->
        <div class="rule-right">
          <rule-action-section 
            v-model:value="localRule.action"
          />
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <template #footer>
        <div class="modal-footer">
          <n-space>
            <n-button @click="$emit('update:show', false)">取消</n-button>
            <n-button 
              type="primary" 
              @click="handleSave"
              :disabled="!canSave"
              :loading="saving"
            >
              保存
            </n-button>
          </n-space>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { NModal, NCard, NButton, NIcon, NSpace } from 'naive-ui';
import CloseOutline from '@vicons/ionicons5/Close';
import type { Rule } from '../../types';
import RuleNameEditor from './RuleNameEditor.vue';
import RuleConditionSection from './RuleConditionSection.vue';
import RuleActionSection from './RuleActionSection.vue';

const props = defineProps<{
  show: boolean;
  editingRule?: Rule | null;
  saving?: boolean;
}>();

const emit = defineEmits<{
  'update:show': [value: boolean];
  save: [rule: Partial<Rule>];
}>();

// 本地规则数据
const localRule = ref({
  name: '',
  condition: '',
  action: 'function main(req, resp, nf) {\n  // 在这里编写规则行为代码\n}'
});

// 条件错误
const conditionError = ref('');

// 监听编辑规则变化
watch(() => props.editingRule, (newRule) => {
  if (newRule) {
    // 尝试从不同的可能格式中提取条件
    let conditionText = '';
    if (newRule.conditions && newRule.conditions.length > 0) {
      const firstCondition = newRule.conditions[0] as any;
      // 尝试不同的字段名
      conditionText = firstCondition.value || firstCondition.expression || firstCondition.condition || '';
    }
    
    // 尝试从不同的可能格式中提取行为
    let actionText = 'function main(req, resp, nf) {\n  // 在这里编写规则行为代码\n}';
    if (newRule.actions && newRule.actions.length > 0) {
      const firstAction = newRule.actions[0] as any;
      actionText = firstAction.script || firstAction.code || actionText;
    }
    
    localRule.value = {
      name: newRule.name || '',
      condition: conditionText,
      action: actionText
    };
  } else {
    localRule.value = {
      name: '',
      condition: '',
      action: 'function main(req, resp, nf) {\n  // 在这里编写规则行为代码\n}'
    };
  }
}, { immediate: true });

// 监听模态框显示状态，确保在显示时重新加载数据
watch(() => props.show, (isShown) => {
  if (isShown && props.editingRule) {
    // 触发规则数据重新加载
    const rule = props.editingRule;
    
    let conditionText = '';
    if (rule.conditions && rule.conditions.length > 0) {
      const firstCondition = rule.conditions[0] as any;
      conditionText = firstCondition.value || firstCondition.expression || firstCondition.condition || '';
    }
    
    let actionText = 'function main(req, resp, nf) {\n  // 在这里编写规则行为代码\n}';
    if (rule.actions && rule.actions.length > 0) {
      const firstAction = rule.actions[0] as any;
      actionText = firstAction.script || firstAction.code || actionText;
    }
    
    localRule.value = {
      name: rule.name || '',
      condition: conditionText,
      action: actionText
    };
  }
});

// 是否可以保存
const canSave = computed(() => {
  return localRule.value.name.trim() && !conditionError.value;
});

// 处理条件错误
const handleConditionError = (error: string) => {
  conditionError.value = error;
};

// 保存规则
const handleSave = () => {
  const rule: Partial<Rule> = {
    name: localRule.value.name.trim(),
    conditions: localRule.value.condition ? [{
      value: localRule.value.condition,
      operator: 'contains'
    }] : [],
    actions: [{
      type: 'script',
      script: localRule.value.action,
      enabled: true
    }]
  };

  if (props.editingRule) {
    rule.id = props.editingRule.id;
  }

  emit('save', rule);
};
</script>

<style scoped>
.rule-name-section {
  margin-bottom: 24px;
}

.rule-content {
  display: flex;
  gap: 24px;
  height: 600px;
}

.rule-left,
.rule-right {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.rule-left {
  min-width: 0; /* 防止flex子项溢出 */
}

.rule-right {
  min-width: 0; /* 防止flex子项溢出 */
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 